package org.jetnuke.modules.feedback;

import org.apache.log4j.Logger;

import java.util.Date;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.concurrent.executor.QueuedExecutor;
import net.jforum.util.mail.EmailException;
import net.jforum.util.mail.EmailSenderTask;
import net.jforum.util.mail.Spammer;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.entities.MainConfig;
import org.jetnuke.util.JetUtil;

public class Send implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Send.class);

	String sender_name, mail, subject, text;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jetnuke.common.IAction#exec(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse,
	 *      org.apache.velocity.VelocityContext, org.jetnuke.common.IModuleInfo,
	 *      java.lang.String, org.jetnuke.common.IUserInfo,
	 *      org.jetnuke.common.IAdminInfo)
	 */
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		MainConfig config = (MainConfig) request.getAttribute("MAIN_CONFIG");
		/*
		 * Session mailSession =
		 * (Session)request.getSession(true).getServletContext().getAttribute("mailSession");
		 * 
		 * Message message = new MimeMessage(mailSession); InternetAddress ia =
		 * new InternetAddress(mail); ia.setPersonal(sender_name);
		 * message.setFrom(ia); message.setRecipient(Message.RecipientType.TO,
		 * new InternetAddress( config.getADMINMAIL()));
		 * message.setSubject(subject); message.setContent("<html><body>"+text+"<body></html>","text/html");
		 *  // Send the message Transport.send(message);
		 */
		String txt = "<html><body>" + text + "<body></html>";

		// try {
		QueuedExecutor.getInstance().execute(
				new EmailSenderTask(new FeedbackSpammer(subject, txt, mail,
						sender_name, config.getADMINMAIL())));

		// new LostPasswordSpammer(user,
		// SystemGlobals.getValue(ConfigKeys.MAIL_LOST_PASSWORD_SUBJECT))));
		// }
		// catch (EmailException e) {
		// logger.warn("Error while sending email: " + e);
		// }

		JetUtil.redirect(vc, response, request.getContextPath()
				+ "/do/feedback/sent");

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

	class FeedbackSpammer extends Spammer {
		String subject1, txt, senderMail, authorName, recipient;
		MimeMessage message;

		public FeedbackSpammer(String subject1, String txt, String senderMail,
				String authorName, String recipient) {
			this.subject1 = subject1;
			this.txt = txt;
			this.senderMail = senderMail;
			this.authorName = authorName;
			this.recipient = recipient;

			message = new MimeMessage(Spammer.getSession());

			try {
				InternetAddress[] recipients = new InternetAddress[1];
				recipients[0] = new InternetAddress(recipient);

				String charset = SystemGlobals
						.getValue(ConfigKeys.MAIL_CHARSET);

				this.message.setSentDate(new Date());
				InternetAddress ia = new InternetAddress(mail);
				ia.setPersonal(sender_name);

				this.message.setFrom(ia);
				this.message.setSubject(subject, charset);

				this.message.setContent(txt, "text/html; charset=" + charset);

				this.message
						.setRecipients(Message.RecipientType.TO, recipients);
			} catch (Exception e) {
				logger
						.error(
								"FeedbackSpammer(String, String, String, String, String)", e); //$NON-NLS-1$

				// logger.warn("EmailException: "+ e);
				throw new EmailException(e);
			}
		}

		public boolean dispatchMessages() throws Exception {
			if (logger.isDebugEnabled()) {
				logger.debug("dispatchMessages() - start"); //$NON-NLS-1$
			}

			String username = SystemGlobals
					.getValue(ConfigKeys.MAIL_SMTP_USERNAME);
			String password = SystemGlobals
					.getValue(ConfigKeys.MAIL_SMTP_PASSWORD);

			if (SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_AUTH)) {
				if (username != null && !username.equals("")
						&& password != null && !password.equals("")) {
					Transport transport = Spammer.getSession().getTransport(
							"smtp");

					try {
						transport.connect(SystemGlobals
								.getValue(ConfigKeys.MAIL_SMTP_HOST), username,
								password);
					} catch (MessagingException e) {
						logger.error("dispatchMessages()", e); //$NON-NLS-1$

						throw new EmailException(
								"Could not connect to the mail server", e);
					}

					if (transport.isConnected()) {
						Address[] addresses = message.getAllRecipients();
						for (int i = 0; i < addresses.length; i++) {
							// Tricks and tricks
							message.setRecipient(Message.RecipientType.TO,
									addresses[i]);
							transport.sendMessage(message,
									new Address[] { addresses[i] });
						}
					}
				}
			} else {
				Address[] addresses = message.getAllRecipients();
				for (int i = 0; i < addresses.length; i++) {
					message
							.setRecipient(Message.RecipientType.TO,
									addresses[i]);
					Transport.send(message, new Address[] { addresses[i] });
				}
			}

			if (logger.isDebugEnabled()) {
				logger.debug("dispatchMessages() - end"); //$NON-NLS-1$
			}
			return true;
		}

	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	public void setSender_name(String sender_name) {
		this.sender_name = sender_name;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public void setText(String text) {
		this.text = text;
	}
}
